var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.startTime').each(function(){
    laydate.render({
        elem: this
    });
});
let productInfo = [];
table.render({
    elem: '#purchaseorder'
    , url: 'complaint/getContractByPage'
    ,cols: [[
        {checkbox: true, fixed: true,title:'选择'}
        ,{field:'customerName', title:'客户名称'}
        ,{field:'customerContractNo', title:'客户合同号',sort:true}
        ,{field:'contractNo', title:'销售合同号',sort:true}
        ,{field:'companyDept', title:'签约单位'}
        ,{field:'bank', title:'银行'}
        ,{field:'createTime', title:'创建日期',sort:true, templet: function(d) {return layui.util.toDateString(d.createTime,"yyyy-MM-dd");}}
        ,{field:'carryTime', title:'出运日期',sort:true, templet: function(d) {return layui.util.toDateString(d.carryTime,"yyyy-MM-dd");}}
    ]]
    ,id: 'purchaseordertableid'
    ,height: 300
    ,page: true
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,data:productInfo
            ,url:"complaint/getContractProductByPage"
            ,cols: [[
                {checkbox: true, fixed: true,title:'选择'}
                ,{field:'productNo', title:'产品编码'}
                ,{field:'specNo', title:'规格编码', width: 120,style:"overflow:hidden"}
                ,{field:'normExplain', title:'规格说明', width: 120,style:"overflow:hidden"}
                ,{field:'chineseName', title:'中文名称', width: 120,style:"overflow:hidden"}
                ,{field:'englishName', title:'英文名称', width: 120,style:"overflow:hidden"}
                ,{field:'unit', title:'单位'}
                ,{field:'colour', title:'颜色'}
                ,{field:'price', title:'单价'}
                ,{field:'amount', title:'数量'}
                ,{field:'customerArticleNo', title:'客户货号',sort:true}
                ,{field:'contractNo', title:'销售合同号',sort:true}
            ]]
            ,id: 'producttableid'
            ,where: {
                contractId:res.data.length == 0 ? "":res.data[0].id //默认第一条信息，数据为空则id为空
            }
            ,height: 400
        });
    }
});

//监听复选框主表
table.on('checkbox(purchaseordertable)', function (data) {
    if(data.type == 'all'){
        //allDataOperation(data);
    }else if(data.type == 'one'){
        oneDataOperation(data);
    }

});

function allDataOperation(data) {
    //第一个表格选中的数据
    let parentTableCheckedData =   table.checkStatus("purchaseordertableid").data;
    if(parentTableCheckedData.length > 0){
        let ids = [];
        for(let i in parentTableCheckedData){
            ids.push(parentTableCheckedData[i].id);
        }
        let datas = JSON.stringify(ids);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"complaint/getProductInfoByContractIds",
            success:function(res){
                if(res.status == 200){
                    let stockData = res.data;
                    //获取被选中的子表数据
                    addCheckedToChangeList(stockData, data.checked);
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }
}

//获取被选中的子表数据
function addCheckedToChangeList(checkedChildData, checkFlag) {
    if(checkedChildData.length > 0){
        let temp = [];
        for (let i in changeList) {
            for (let j in checkedChildData) {
                let flag = checkedChildData[j].id == changeList[i].contractId;
                if (!flag && checkFlag) {
                    let child = $("#product").next().find('tbody input[type="checkbox"]');
                    child.each(function(index, item){
                        item.checked = checkFlag;
                    });
                    temp.push(checkedChildData[j]);
                }
                if(flag && !checkFlag){
                    changeList.splice(i,1);
                }
            }
        }
        if(temp.length > 0){
            changeList.push.apply(changeList, temp);
        }
    }
}

function oneDataOperation(data) {
    let id = data.data.id;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1
        }
        ,where: {
            contractId:id
        },
        done: function (res, curr, count) {
            let child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(res.data!=null){
                if(data.checked){
                    for(let i = 0; i < res.data.length; i++){
                        res.data[i].customerName=data.data.customerName;
                        res.data[i].companyDept=data.data.companyDept;
                        res.data[i].bank=data.data.bank;
                        changeList.push(res.data[i]);
                    }
                }else{
                    if(changeList.length > 0){
                        for(let i = 0; i < res.data.length; i++){
                            deleteData(res.data[i]);
                        }
                    }
                }
            }
            form.render('checkbox');
        }
    }, 'data');
}

function deleteData(data){
    let id = data.contractId;
    for(let j = 0; j < changeList.length; j++){
        if (changeList[j].contractId == id) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}

//子表单全选,则对应选中或取消
function checkedParent(tableCache, flag){
    //主表数据
    let parentData = layui.table.cache["purchaseordertableid"];
    if(tableCache.length > 0 && parentData.length > 0){
        //对应主表id
        let id = tableCache[0].id;
        for (let i in parentData) {
            if(parentData[i].contractId == id){
                if(flag){
                    parentData.data[i].LAY_CHECKED = 'true';
                    return false;
                }else{
                    parentData.data[i].LAY_CHECKED = 'false';
                    return false;
                }
            }
            return false;
        }
    }
    //重新加载主表
    table.reload('purchaseordertableid', {data:parentData});
}

//复选框子表
table.on('checkbox(producttable)', function (obj) {
    if ( obj.type == 'one' ) {
        if (obj.checked) {
            changeList.push(obj.data);
        } else {
            for (let index in changeList) {
                if (changeList[index].contractId == obj.data.contractId) {
                    changeList.splice(index,1);
                }
            }
        }
    } else if (obj.type == 'all') {
        let tableCache = table.checkStatus("producttableid").data;
    }
    form.render('checkbox');
});

//单击行事件
table.on('row(purchaseordertable)', function (obj) {
    let id = obj.data.id;
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            contractId:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].contractId == res.data[i].contractId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
       done: function (res, curr, count) {

        }
    }, 'data');

});

//提交查询条件
form.on('submit(submitform)', function(data){
    let resultData = {};
    if(data.field.contractNo != '' ) {resultData.contractNo = data.field.contractNo;}
    if(data.field.customerContractNo != '' ) {resultData.customerContractNo = data.field.customerContractNo;}
    if(data.field.createTime != '' ) {resultData.createTime = data.field.createTime;}
    if(data.field.customerName != '' ) {resultData.customerName = data.field.customerName;}
    if(data.field.carryTime != '' ) {resultData.carryTime = data.field.carryTime;}
    table.reload('purchaseordertableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: resultData
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        let oldData =  parent.table.cache["storageproductstableid"];
        let newData = [];
        let num = oldData.length+1;
        for(let i in changeList){
            changeList[i].tempId = num;
            newData.push(changeList[i]);
            num++;
        }
        oldData.push.apply(oldData, newData);
        parent.table.reload('storageproductstableid', {data:oldData});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})
$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})